<template>
  <div class="bg-box" v-if="list.length > 1">
    <div class="right">
      <t-radio-group size="small" variant="default-filled" v-model="type" @change="update">
        <t-radio-button v-for="(item, index) in plugin.tm('order.right')" :value="index">{{ item }}</t-radio-button>
      </t-radio-group>
    </div>
    <div class="title">
      {{ plugin.t('order.title') }}
    </div>
    <Charts ref="charts" style="height: 400px;" :option="option" />
  </div>
</template>
<script setup>
  import { ref, watch } from 'vue'
  import app from '@/app'
  import index from '../../index'
  import Charts from '@/components/charts.vue'

  const plugin = index.plugin
  const props = defineProps(['list', 'time'])
  const charts = ref()
  const option = ref({})
  const type = ref(0)

  const getData = (name) => props.list.map(item => item[name] ?? 0)

  const build = (series, format) => {
    return {
      tooltip: {
        trigger: 'axis',
        valueFormatter: value => format ? app.money.format(value) : value
      },
      legend: {
        bottom: 'bottom'
      },
      xAxis: {
        type: 'category',
        data: props.time
      },
      yAxis: [{
        type: 'value',
        position: 'left',
        alignTicks: true,
        axisLabel: {
          formatter: value => format ? app.money.format(value) : value
        }
      }],
      grid: {
        left: 0,
        right: 0,
        top: 20,
        bottom: 40,
        containLabel: true
      },
      series: series
    }
  }

  const update = () => {
    if(charts.value) {
      charts.value.clear()
    }
    option.value = [
      () => build([
        {
          name: plugin.t('order.total'),
          type: 'bar',
          data: getData('t'),
          itemStyle: {
            borderRadius: [3, 3, 0, 0]
          }
        }, {
          name: plugin.t('order.profit_money'),
          type: 'bar',
          data: getData('pm'),
          itemStyle: {
            borderRadius: [3, 3, 0, 0]
          }
        }
      ], true), 
      () => build({
        name: plugin.t('order.count'),
        type: 'bar',
        data: getData('c'),
        itemStyle: {
          borderRadius: [3, 3, 0, 0]
        }
      }, false)
    ][type.value]()
  }

  watch(props, () => {
    update()
  })

  update()
</script>